<template>
  <div class="white-box">
    <div class="task-one">
      <div class="task-one__item">
        <span class="task-one__label">微信昵称：</span>
        <el-input placeholder="请输入微信昵称" v-model="searchParams.nickName" @keyup.enter.native="handleSearch" clearable></el-input>
      </div>
      <div class="task-one__item">
        <span class="task-one__label">会员名：</span>
        <el-input placeholder="请输入会员名" v-model="searchParams.memberName" @keyup.enter.native="handleSearch" clearable></el-input>
      </div>
      <div class="task-one__item">
        <span class="task-one__label">手机号：</span>
        <el-input placeholder="请输入手机号" v-model="searchParams.memberPhone" @keyup.enter.native="handleSearch" clearable></el-input>
      </div>
      <div class="task-one__item">
        <span class="task-one__label">性别：</span>
        <el-select v-model="searchParams.sex" placeholder="请选择性别" clearable>
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.sex"
                     :key="index"/>
        </el-select>
      </div>
      <div class="task-one__item">
        <span class="task-one__label">会员等级：</span>
        <el-select v-model="searchParams.gradeId" placeholder="请选择会员等级" clearable>
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.gradeId"
                     :key="index"/>
        </el-select>
      </div>
      <div class="task-one__item">
        <span class="task-one__label">会员分组：</span>
        <el-select v-model="searchParams.groupId" placeholder="请选择会员分组" clearable>
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.groupId"
                     :key="index"/>
        </el-select>
      </div>
      <div class="task-one__item">
        <span class="task-one__label">状态：</span>
        <el-select v-model="searchParams.status" placeholder="请选择状态" clearable>
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.status"
                     :key="index"/>
        </el-select>
      </div>
      <div class="task-one__btn task-wrap-btn clearfix ">
        <el-button type="primary" :loading="searchBtnLoading" :icon="Search"
                   @click="handleSearch">搜索</el-button>
      </div>
    </div>
    <div style="margin-bottom: 20px">
      <el-popconfirm :persistent="false" :title="`确定删除勾选的${selectedIds.length}条数据？`" confirm-button-text="确定" cancel-button-text="取消"
                     @confirm="handleDelete(selectedIds)">
        <template #reference>
          <el-button type="default" plain size="small">批量删除</el-button>
        </template>
      </el-popconfirm>
<!--      <el-button type="default" plain size="small">设置分组</el-button>-->
<!--      <el-button type="default" plain size="small">设置等级</el-button>-->
    </div>
    <el-table class="table-mb" v-loading="loading" :data="list" :header-cell-style="{ background: '#F5F7FA' }"
              element-loading-background="rgba(255, 255, 255, 0.6)"  row-key="sid" @select="handleSelected" @select-all="handleAllSelected">
      <el-table-column type="selection" width="55" />
<!--      <el-table-column prop="sid" label="sid" width="50"></el-table-column>-->
      <el-table-column prop="headimgUrl" label="头像" min-width="66" max-width="66" width="66">
        <template #default="{ row }">
          <el-avatar :size="50" :src="row.headimgUrl" style="display: block"/>
        </template>
      </el-table-column>
      <el-table-column prop="memberName" label="会员">
        <template #default="{ row }">
          <div style="display: flex;align-items: center">
            <span>{{row.memberName}}</span>
            <el-icon v-if="row.sex === 0">
              <Male color="#409eff"/>
            </el-icon>
            <el-icon v-if="row.sex === 1">
              <Female color="#f89898"/>
            </el-icon>
          </div>
          <div><el-text type="info">ID：</el-text>{{row.id}}</div>
          <div><el-text type="info">微信昵称：</el-text>{{row.nickName}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="memberType" label="基础信息">
        <template #default="{ row }">
          <div>
            <el-text type="info">类型：</el-text>
            <el-text type="warning" v-if="row.memberType === 2">分销商</el-text>
            <el-text type="primary" v-if="row.memberType === 1">用户</el-text>
          </div>
          <div><el-text type="info">等级：</el-text>{{row.gradeName}}</div>
          <div><el-text type="info">分组：</el-text>{{row.groupName}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="payMoney" label="统计">
        <template #default="{ row }">
          <div><el-text type="info">消费总额：</el-text>￥{{row.payMoney}}</div>
          <div><el-text type="info">消费次数：</el-text>{{row.payNum}}</div>
          <div><el-text type="info">最近消费时间：</el-text>{{row.payDate}}</div>
        </template>
      </el-table-column>
<!--      <el-table-column prop="nickName" label="下级会员数">-->
<!--        <template #default="{ row }">-->

<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column align="center" prop="status" label="状态"  width="100">
        <template #default="{ row }">
          <el-text v-if="row.status === 0" type="success">正常</el-text>
          <el-text v-else-if="row.status === 1" type="info">停用</el-text>
          <el-text v-else type="info"></el-text>
        </template>
      </el-table-column>
      <el-table-column prop="created" label="创建时间" width="160"> </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <div style="margin-bottom: 4px">
            <el-button link type="primary" @click="handleEdit(row,{sid:row.sid})">编辑信息</el-button>
            <el-popconfirm :persistent="false" title="确定删除吗？" confirm-button-text="确定" cancel-button-text="取消"
                           @confirm="handleDelete(row.sid)">
              <template #reference>
                <el-button link type="danger">删除用户</el-button>
              </template>
            </el-popconfirm>
          </div>
          <div style="margin-bottom: 4px">
            <el-button link type="success" @click="setMemberGroup(row)">设置分组</el-button>
            <el-button link type="success" @click="setMemberGrade(row)">设置等级</el-button>
          </div>
          <div>
            <el-button link type="success" @click="handleSetParent(row)">设置上级</el-button>
            <el-button link type="success" @click="handleAction('put',`/member/setDistributor/${row.sid}`)" v-if="row.memberType != 2">设为分销商</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="pageSizeNum"
        :total="totalNums"
        layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <el-dialog v-model="dialogShow" :title="dialogParams.type === 'add'?'添加':'编辑'" width="660px" :append-to-body="true" :destroy-on-close="true" :close-on-click-modal="false" @close="closeDialog">
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogFormRules" label-width="120px" style="width: 550px">
        <el-form-item label="会员名" prop="memberName" required>
          <el-input v-model.trim="dialogForm.memberName" clearable placeholder="请输入会员名" maxlength="20"/>
        </el-form-item>
        <el-form-item label="微信昵称" prop="nickName">
          <el-input v-model.trim="dialogForm.nickName" clearable placeholder="请输入微信昵称" maxlength="20"/>
        </el-form-item>
        <el-form-item label="头像" prop="headimgUrl">
          <el-input v-model.trim="dialogForm.headimgUrl" clearable placeholder="请输入头像"/>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
              v-model="dialogForm.birthday"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
          />
        </el-form-item>
        <el-form-item label="手机号" prop="memberPhone">
          <el-input v-model.trim="dialogForm.memberPhone" maxlength="11" clearable placeholder="请输入手机号" oninput="value=value.replace(/[^\d]/g,'')"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="dialogForm.sex">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
            <el-radio :value="2">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dialogForm.status">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <div class="flexs">
            <el-button type="primary" :loading="dialogParams.loading" @click="submitDialogForm(dialogFormRef)">
              确认
            </el-button>
            <el-button @click="resetDialogForm(dialogFormRef)">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog v-model="group_dialogShow" title="设置分组" width="660px" :append-to-body="true" :destroy-on-close="true" :close-on-click-modal="false" @close="group_closeDialog">
      <el-form ref="group_dialogFormRef" :model="group_dialogForm" :rules="group_dialogFormRules" label-width="120px"  style="width: 550px">
        <el-form-item label="姓名">
          <span>{{group_dialogParams.row.memberName}}</span>
        </el-form-item>
        <el-form-item label="分组名称" prop="groupId" required>
          <el-select v-model="group_dialogForm.groupId" placeholder="请选择分组" clearable>
            <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.groupId"
                       :key="index"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="flexs">
            <el-button type="primary" :loading="group_dialogParams.loading" @click="group_submitDialogForm()">
              确认
            </el-button>
            <el-button @click="resetDialogForm(group_dialogFormRef)">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog v-model="grade_dialogShow" title="设置等级" width="660px" :append-to-body="true" :destroy-on-close="true" :close-on-click-modal="false" @close="grade_closeDialog">
      <el-form ref="grade_dialogFormRef" :model="grade_dialogForm" :rules="grade_dialogFormRules" label-width="120px"  style="width: 550px">
        <el-form-item label="姓名">
          <span>{{grade_dialogParams.row.memberName}}</span>
        </el-form-item>
        <el-form-item label="等级名称" prop="gradeId" required>
          <el-select v-model="grade_dialogForm.gradeId" placeholder="请选择等级" clearable>
            <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.gradeId"
                       :key="index"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="flexs">
            <el-button type="primary" :loading="grade_dialogParams.loading" @click="grade_submitDialogForm()">
              确认
            </el-button>
            <el-button @click="resetDialogForm(grade_dialogFormRef)">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--设置上级-->
    <setParent :show="setParentShow" :data="setParentData" @close="closeSetParent"></setParent>

    <go-back/>
  </div>
</template>

<script setup>
import {
  getCurrentInstance,
  ref,
  reactive,
  onMounted,
  watch,
  computed
} from "vue"
import listMixins from "@mixins/hook/list"
import {
  useRouter
} from "vue-router"
import {
  CirclePlus, Download, Lock, Search
} from "@element-plus/icons-vue"
import GoBack from "@components/GoBack.vue"
import setParent from "./components/setParent.vue";
const router = useRouter()
const {
  proxy
} = getCurrentInstance()

/**
 * minxin列表加载
 */
const {
  page,
  pageSizeNum,
  pageSize,
  loading,
  totalNums,
  searchParams,
  searchBtnLoading,
  apiPath,
  list,
  dialogFormRef,
  dialogShow,
  dialogForm,
  dialogParams,
  selectedIds,
  handleSearch,
  getData,
  handleAdd,
  handleEdit,
  resetDialogForm,
  handleAllSelected,
  handleSelected,
  submitDialogForm,
  closeDialog,
  handleAction,
  handleDelete,
} = listMixins()

const selectOptions = reactive({
  roleSids:[],
  sex:[
    {label:'未知',value:2},
    {label:'男',value:0},
    {label:'女',value:1},
  ],
  status:[
    {label:'正常',value:0},
    {label:'停用',value:1},
  ],
  groupId:[],
  gradeId:[]
})

dialogForm.headimgUrl = "";//头像
dialogForm.birthday = "";//生日：yyyy-MM-dd
dialogForm.idCard = "";//身份证号码
dialogForm.memberName = "";//会员名称，支持中文、英文大小写、数字及下划线_，2-20字符
dialogForm.memberPhone	= "";//手机号，11位
dialogForm.nickName	= '';//微信昵称
dialogForm.sex = 2;//性别：0=男, 1=女, 2=未知；默认2
dialogForm.status	= 0;//状态：0=正常, 1=停用；默认0

apiPath.value = '/member';

onMounted(() => {
  getData()
  getGroup();
  getGrade();
})
const dialogFormRules = reactive({
  memberName:[{
    required: true,
    message: "请输入姓名",
    trigger: "blur"
  }],
})
// 设置分组
const setMemberGroup = (row) =>{
  group_dialogParams.row = row;
  group_dialogShow.value = true;
}
const group_dialogFormRules = reactive({
  groupId:[{
    required: true,
    message: "请选择",
    trigger: "blur"
  }]
})
const group_dialogFormRef = ref(null);
const group_dialogShow = ref(false);
const group_dialogParams = reactive({
  loading:false,
  row:{}
});
const group_dialogForm = reactive({
  groupId:''
})
const group_submitDialogForm = () => {
  group_dialogFormRef.value.validate((valid, fields) => {
    if (valid) {
      group_dialogParams.loading = true;
      let data = JSON.parse(JSON.stringify(group_dialogParams.row));
      delete data.sid
      let groupId = group_dialogForm.groupId;
      let sid = group_dialogParams.row.sid;
      proxy.$axios.put(`/member/setMemberGroup/${sid}/${groupId}`,data)
          .then((res) => {
            group_dialogParams.loading = false
            if (res.data.code == 200) {
              group_closeDialog()
              proxy.$message({
                message: `修改成功`,
                type: "success"
              })
              getData()
            } else {
              proxy.$message({
                message: res.data.msg,
                type: "error"
              })
            }
          })
          .catch((err) => {
            group_dialogParams.loading = false
          })
    }
  })
}
const group_closeDialog = () => {
  group_dialogShow.value = false
  resetDialogForm(group_dialogFormRef.value)
}
// 设置分组-end

// 设置等级
const setMemberGrade = (row) =>{
  grade_dialogParams.row = row;
  grade_dialogShow.value = true;
}
const grade_dialogFormRules = reactive({
  gradeId:[{
    required: true,
    message: "请选择",
    trigger: "blur"
  }]
})
const grade_dialogFormRef = ref(null);
const grade_dialogShow = ref(false);
const grade_dialogParams = reactive({
  loading:false,
  row:{}
});
const grade_dialogForm = reactive({
  gradeId:''
})
const grade_submitDialogForm = () => {
  grade_dialogFormRef.value.validate((valid, fields) => {
    if (valid) {
      grade_dialogParams.loading = true;
      let data = JSON.parse(JSON.stringify(grade_dialogParams.row));
      delete data.sid;
      let gradeId = grade_dialogForm.gradeId;
      let sid = grade_dialogParams.row.sid;
      proxy.$axios.put(`/member/setMemberGrade/${sid}/${gradeId}`,data)
          .then((res) => {
            grade_dialogParams.loading = false
            if (res.data.code == 200) {
              grade_closeDialog()
              proxy.$message({
                message: `修改成功`,
                type: "success"
              })
              getData()
            } else {
              proxy.$message({
                message: res.data.msg,
                type: "error"
              })
            }
          })
          .catch((err) => {
            grade_dialogParams.loading = false
          })
    }
  })
}
const grade_closeDialog = () => {
  grade_dialogShow.value = false
  resetDialogForm(grade_dialogFormRef.value)
}
// 设置等级-end

// 设置上级
const setParentShow = ref(false)
const setParentData = ref({})
const closeSetParent =(isSubmit)=>{
  setParentShow.value = false
  if(isSubmit){
    getData()
  }
}
const handleSetParent = (row)=>{
  setParentShow.value = true
  setParentData.value = row;
}
// 设置上级-end
const getGroup = async () => {
  // todo 接口带分页 待修改
  await proxy.$axios
      .get('/member/group')
      .then((res) => {
        switch (res.data.code) {
          case 200:
            let resData = res.data.data.records
            selectOptions.groupId = resData.map(v=>{
              return {
                label:v.groupName,
                value:v.sid
              }
            })
            break
          default:
            proxy.$message({message: res.data.msg, type: "error"})
            break
        }
      })
      .catch((error) => {
      })
}

const getGrade = async () =>{
  // todo 接口带分页 待修改
  await proxy.$axios
      .get('/member/grade')
      .then((res) => {
        switch (res.data.code) {
          case 200:
            let resData = res.data.data.records
            selectOptions.gradeId = resData.map(v=>{
              return {
                label:v.gradeName,
                value:v.sid
              }
            })
            break
          default:
            proxy.$message({message: res.data.msg, type: "error"})
            break
        }
      })
      .catch((error) => {
      })
}

</script>

<style lang="less">

</style>